package mycinema.dao.impl;

import java.sql.Date;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import sun.applet.Main;

import mycinema.dao.BaseDao;
import mycinema.dao.MovieDao;
import mycinema.entity.Movie;

public class MovieDaoImpl extends BaseDao implements MovieDao{

	public List<Movie> getMovies(int cid, String title, int pageSize, int page) {
		List<Movie> list = new ArrayList<Movie>();
		ArrayList sqlLsit = new ArrayList();
		String sqlA = "select * from Movie where 1=1 ";
		if(cid>0){
			sqlA += "and categoryid = ?";
			sqlLsit.add(cid);
		}
		if(title != null && !title.isEmpty()){
			sqlA += "and title like ?";
			sqlLsit.add("%"+title+"%");
		}
		String sqlB = " order by id limit ? , ?";
		sqlLsit.add((page-1)*pageSize);
		sqlLsit.add(pageSize);
		String sql = sqlA+sqlB;
		ResultSet rs = null ;
		
		this.openConnection();
		try {
			rs = this.executeQuery(sql, sqlLsit.toArray());
			while(rs.next()){
				
				int id = rs.getInt("id");
				String movieCode = rs.getString("moviecode");
				int caid = rs.getInt("categoryid");
				String mtitle = rs.getString("title");
				String director = rs.getString("director");
				Date date = rs.getDate("datereleased");
				Movie m = new Movie(id, movieCode, cid, mtitle, director, date);
				list.add(m);
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return list;
	}

	public int getMovieRows(int cid, String title) {
		int rows = 0;
		String sql = "select count(*) from movie where 1 = 1 ";
		ArrayList list = new ArrayList();
		if(cid>0){
			sql += "and categoryid = ?";
			list.add(cid);
		}
		if(title != null && !title.isEmpty()){
			sql += "and title like ?";
			list.add("%"+title+"%");
		}
		ResultSet rs = null ;
		
		this.openConnection();
		try {
			rs = this.executeQuery(sql, list.toArray());
			if(rs.next()){
				rows = rs.getInt(1);
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			closeResource();
		}
		
		return rows;
	}

	public static void main(String[] args) {
		MovieDaoImpl dao = new MovieDaoImpl();
		List<Movie> list = dao.getMovies(0, "狂", 5, 1);
		for(Movie m : list){
			System.out.println(m.getId()+"\t"+m.getTitle()+"\t"+m.getDirector());
		}
		int rows = dao.getMovieRows(0, "");
		System.out.println(rows);
	}
}
